package com.netty.bfport.http.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.netty.bfport.http.common.es.EsUtils;
import com.netty.bfport.http.domain.dto.HealthyHistoryDTO;
import com.netty.bfport.http.domain.dto.TUserDTO;
import com.netty.bfport.http.mapper.PersonInfoMapper;
import com.netty.bfport.http.service.PersonInfoService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @Author: zhaoyang05
 * @Data: 2022/3/23 13:20
 * @Description
 */
@Service
public class PersonInfoServiceImpl implements PersonInfoService {
    @Resource
    PersonInfoMapper personInfoMapper;
    @Resource
    EsUtils esUtils;

    @Override
    public PageInfo<TUserDTO> userList(String name, String telephone, Integer page, Integer size) {
        PageHelper.startPage(page,size);
        return new PageInfo<>(personInfoMapper.userList(name, telephone));
    }

    @Override
    public int userAdd(TUserDTO tUserDTO) {
        tUserDTO.setCreateTime(new Date());
        return personInfoMapper.userAdd(tUserDTO);
    }

    @Override
    public int userUp(TUserDTO tUserDTO) {
        return personInfoMapper.userUp(tUserDTO);
    }

    @Override
    public List<HealthyHistoryDTO> healthyList(String userId, Date time) throws IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return esUtils.searchHistoryHealthy(userId,getStartOfDay(time),getEndOfDay(time),"fz" + sdf.format(time));
    }

    /**
     * 获取入参时间的当天0：00的时间戳
     * @param time Date类型时间
     * @return time的当天0：00的时间戳long类型
     * */
    public static Long getStartOfDay(Date time) {
        if (time==null)time = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(time);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime().getTime();
    }
    /**
     * 获取入参时间的当天23：59的时间戳
     * @param time Date类型时间
     * @return time的当天23：59的时间戳long类型
     * */
    public static Long getEndOfDay(Date time) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(time);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        return calendar.getTime().getTime();
    }
}
